<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--门店数据-->
        <pane size="16">
          <el-col>
            <el-tree
              ref="tree"
              class="filter-tree"
              :props="defaultProps"
              lazy
              accordion
              :load="loadNode"
              @node-click="nodeClick"
            />
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <!-- 门店列表 -->
            <TableList
              v-if="currentLevel === 1"
              key="store"
              ref="TableList"
              :model-value="searchFormData"
              request-url="system/company/list"
              request-method="get"
              :table-data="tableData"
              :table-column="tableColumn"
              btn-style="padding-left: 0px"
              label-width="70"
              search-style="padding: 0"
              @requestSuccess="storeRequest"
            >
              <!-- 搜索去内容 -->
              <template #search>
                <el-form-item label="门店名称" prop="keyword">
                  <el-input v-model="searchFormData.keyword" autocomplete="off" placeholder="请输入门店名称" size="small" clearable />
                </el-form-item>
              </template>

              <!-- 按钮区 -->
              <template #btns>
                <el-button size="small" type="primary" @click="drawer=true">新增门店</el-button>
              </template>

              <template #accountInfo="{ item, row }">
                <el-button size="mini" type="primary" @click="watchAccountInfo(row)">点击查看管理账号</el-button>
              </template>

              <!-- 图片 -->
              <template #companyImage="{ item, row }">
                <div class="demo-image__preview">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="row[item]"
                    :preview-src-list="[row[item]]"
                  />
                </div>
              </template>

              <template #expand="{row}">
                <div>1</div>
              </template>

              <!-- 自定义operate 列 -->
              <template #operate="{ item, row }">
                <el-button type="text" size="small" @click="handleUpdate(row)">编辑</el-button>
                <el-button type="text" size="small" @click="deleteStore(row)">删除</el-button>
                <el-button type="text" size="small" @click="createAccount(row)">创建账号</el-button>
              </template>

            </TableList>
            <!-- 部门列表 -->
            <TableList
              v-if="currentLevel===2"
              :key="'dept' + currentLevel"
              ref="deptTable"
              :model-value="deptSearchForm"
              request-url="system/company-dept/list"
              :init-params="{companyId: currentItemInfo.id}"
              btn-style="padding-left: 0px"
              label-width="70"
              :table-column="deptTableColumn"
              search-style="padding: 0"
              @requestSuccess="deptListRequest"
            >
              <template #search>
                <el-form-item label="部门名称" prop="keyword">
                  <el-input v-model="deptSearchForm.keyword" autocomplete="off" placeholder="请输入部门名称" size="small" clearable />
                </el-form-item>
              </template>

              <template #store="{ item, row }">
                <div>{{ storeList.find(item => item.id == row['companyId']) ? storeList.find(item => item.id == row['companyId']).companyName : '' }}</div>
              </template>

              <!-- 按钮区 -->
              <template #btns>
                <el-button size="small" type="primary" @click="deptShow=true">新增部门</el-button>
              </template>

              <template #operate="{ item, row }">
                <div style="display: flex; gap: 10px; align-items: center;">
                  <el-button type="text" size="small" @click="deptUpdate(row)">编辑</el-button>
                  <DeleteButton type="text" @delete-item="deptDelete(row)" />
                </div>
              </template>

            </TableList>
            <!-- 员工列表 -->
            <TableList
              v-if="currentLevel===3"
              :key="'staff' + currentLevel"
              ref="staffTable"
              :model-value="staffSearchForm"
              request-url="system/company-user/list"
              :init-params="{companyId: staffValue.companyId, deptId: staffValue.deptId}"
              btn-style="padding-left: 0px"
              label-width="70"
              :table-column="staffTableColumn"
              search-style="padding: 0"
              @requestSuccess="staffListRequest"
            >
              <template #search>
                <el-form-item label="员工名称" prop="keyword">
                  <el-input v-model="staffSearchForm.keyword" autocomplete="off" placeholder="请输入员工" size="small" clearable />
                </el-form-item>
              </template>

              <template #store="{ item, row }">
                <div>{{ storeList.find(item => item.id == row['companyId']) ? storeList.find(item => item.id == row['companyId']).companyName : '' }}</div>
              </template>

              <template #dept="{ item, row }">
                <div>{{ deptList.find(item => item.id == row['deptId']) ? deptList.find(item => item.id == row['deptId']).name : '' }}</div>
              </template>

              <!-- 按钮区 -->
              <template #btns>
                <el-button size="small" type="primary" @click="staffShow=true">添加员工</el-button>
              </template>

              <template #operate="{ item, row }">
                <div style="display: flex; gap: 10px;">
                  <DeleteButton type="text" @delete-item="staffDelete(row)" />
                </div>
              </template>

            </TableList>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 部门的新增/修改 -->
    <AddDept
      :visible="deptShow"
      :default-value="deptValue"
      @close="deptShow = false"
      @add-success="deptAddSuccess"
    />
    <!-- 添加员工弹窗 -->
    <AddStaff
      :visible="staffShow"
      :default-value="staffValue"
      @close="staffShow = false"
      @add-success="staffAddSuccess"
    />
    <!-- 门店的新增/修改 -->
    <Form
      :drawer="drawer"
      :default-value="defaultValue"
      :classify-list="classifyList"
      @add-success="addSuccess"
      @close:drawer="drawer=false"
    />
    <!-- 账号信息的查看 -->
    <AccountInfo
      :id="companyId"
      :visible="accountShow"
      @close="accountShow = false"
    />
    <!-- 创建账号信息 -->
    <CreateAccount
      :id="companyId"
      :visible="createShow"
      @close="createShow = false"
      @add-success="createShow=false"
    />

  </div>
</template>

<script>

import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import TableList from '@/components/TableList'
import Form from './form'
import AccountInfo from './AccountInfo.vue'
import CreateAccount from './CreateAccount'
import AddStaff from './AddStaff.vue'
import AddDept from './AddDept.vue'
import { myMixin } from './data.js'
import { area } from '@/utils/area'
import request from '@/utils/request'

export default {
  components: {
    Splitpanes,
    Pane,
    TableList,
    Form,
    AccountInfo,
    CreateAccount,
    AddDept,
    AddStaff
  },
  mixins: [myMixin],
  data() {
    return {
      drawer: false,
      accountShow: false,
      createShow: false,
      /**  */
      searchFormData: {},
      /** 员工的form */
      staffSearchForm: {},
      /** 部门的form */
      deptSearchForm: {},
      defaultValue: {},
      companyId: 0,
      tableData: [],
      classifyList: [],
      treeData: [

      ],
      defaultProps: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf'
      },
      /** 门店列表的请求列表 */
      storeList: [],
      /** 部门列表的数据 */
      deptList: [],
      /** 员工信息的列表数据 */
      staffList: [],
      /**  */

      /** 记录当前的level */
      currentLevel: 1,
      /** 保存 tree-node 的resolve 状态 */
      treeResolve: { },
      /** 当前点击的 item 的一些信息 */
      currentItemInfo: {},
      /** 新增，修改 部门的 弹出 */
      deptShow: false,
      /** 传入 部门弹窗里面的数据 */
      deptValue: {},
      /**  传入 员工弹窗的数据 */
      staffValue: {},
      /** 当前点击的节点信息 */
      clickItemNode: {},
      /** 当次操作是不是懒加载 */
      isLazy: false,
      /** 添加员工弹窗 */
      staffShow: false,
      deptTableColumn: [
        {
          prop: 'companyId',
          label: '门店ID'
        }, {
          prop: 'name',
          label: '部门名称'
        }, {
          prop: 'employeeCount',
          label: '员工人数'
        }, {
          prop: 'store',
          label: '所属门店'
        }, {
          prop: 'operate',
          label: '操作'
        }
      ],
      staffTableColumn: [
        {
          prop: 'id',
          label: 'ID'
        }, {
          prop: 'userName',
          label: '员工名称'
        }, {
          prop: 'store',
          label: '所属门店'
        }, {
          prop: 'dept',
          label: '所属部门'
        }, {
          prop: 'operate',
          label: '操作'
        }
      ]
    }
  },
  created() {
    this.getClassifyList()
  },
  methods: {
    loadNode(node, resolve) {
      this.isLazy = true
      setTimeout(() => {
        this.isLazy = false
      }, 500)
      if (node.level === 0) {
        return resolve([{ name: '门店列表' }])
      }

      // 门店列表
      if (node.level === 1) {
        this.clickItemNode = node
        this.treeResolve = {
          [node.id]: resolve
        }
        this.currentLevel = node.level
        const d = this.storeList.map(item => ({ name: item.companyName, id: item.id }))
        return resolve(d)
      }

      // 门店列表里面的部门信息
      if (node.level === 2) {
        this.treeResolve = {
          [node.id]: resolve
        }
        setTimeout(() => {
          this.currentLevel = 2
        }, 300)
        this.currentLevel = -1

        this.currentItemInfo = node.data
        this.deptValue = {
          companyName: node.data.name,
          companyId: node.data.id
        }
        return
      }
      if (node.level > 1) return resolve([])
    },
    // 部门列表请求
    getDeptList(id) {
      return new Promise((resolve, reject) => {
        request({ url: 'system/company-dept/list', method: 'get', params: { pageNum: 1, pageSize: 10, companyId: id }}).then(res => {
          if (res.code === 200) {
            this.deptList = res.data.rows
            // console.log(this.deptList, '---')

            resolve(res.data.rows)
          } else {
            resolve([])
          }
        }).catch(() => resolve([]))
      })
    },
    // 门店列表请求成功的回调
    storeRequest(rows) {
      const { clickItemNode, treeResolve } = this
      this.storeList = rows
      const treeList = rows.map(item => ({ name: `${item.companyName}`, id: item.id }))
      treeResolve[clickItemNode.id]?.(treeList)
    },
    addSuccess() {
      this.drawer = false
      this.$refs.TableList?.requestData()
    },
    async handleUpdate(row) {
      this.drawer = true
      this.defaultValue = row
    },
    /**
     * 点击tree 节点
     */
    nodeClick(data, node, com) {
      this.currentItemInfo = node.data
      // 不是懒加载的时候，才走这个切换逻辑
      if (node.level !== 1) {
        setTimeout(() => {
          this.currentLevel = node.level
        }, 300)
        this.currentLevel = -1
      }
      this.clickItemNode = node
      // 点击后，清空表单的数据
      this.searchFormData = {}
      /** 员工的form */
      this.staffSearchForm = {}
      /** 部门的form */
      this.deptSearchForm = {}
      // 点击第三级，获取前面的参数，
      if (node.level === 3) {
        this.staffValue = {
          companyName: node.parent.data.name,
          companyId: node.parent.data.id,
          deptName: node.data.name,
          deptId: node.data.id
        }
      }
    },
    getClassifyList() {
      request({ url: 'system/category/list', method: 'get', params: { pageSize: 1000 }}).then(res => {
        if (res.code == 200) {
          this.classifyList = res.rows.map(item => ({ value: item.category, label: item.category }))
        }
      })
    },
    deleteStore(row) {
      request({ url: 'system/company/delete', method: 'post', data: { id: row.id }}).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000,
            onClose: () => {
              this.$refs.TableList?.requestData()
            }
          })
        }
      })
    },
    watchAccountInfo(row) {
      this.companyId = row.id
      this.accountShow = true
    },
    createAccount(row) {
      this.companyId = row.id
      this.createShow = true
    },
    /** 部门列表的删除 */
    deptDelete(row) {
      request({ url: 'system/company-dept/delete', method: 'post', data: { id: row.id }}).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000,
            onClose: () => {
              this.$refs.deptTable?.requestData()
            }
          })
        }
      })
    },
    /** 部门列表的更新 */
    deptUpdate(row) {
      this.deptShow = true
      this.deptValue = {
        companyName: this.clickItemNode.data.name,
        name: row.name,
        companyId: row.companyId,
        id: row.id
      }
    },
    /** 职员列表请求成功后的回调 */
    deptListRequest(row, type) {
      const { clickItemNode, treeResolve } = this
      const treeList = row.map(item => ({ name: `${item.name}(${item.employeeCount})`, id: item.id, leaf: true, parent: '' }))
      this.deptList = row
      treeResolve[clickItemNode.id]?.(treeList)
    },
    /** 新增部门请求成功 */
    deptAddSuccess() {
      this.$refs.deptTable?.requestData('add')
      this.deptShow = false
    },
    staffAddSuccess() {
      this.staffShow = false
      this.$refs.staffTable?.requestData()
    },
    staffListRequest(rows) {
      console.log(rows, '---')

      this.staffList = rows
    },
    // 删除员工
    staffDelete(row) {
      request({ url: '/system/company-user/remove', method: 'post', data: { id: row.id }}).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000,
            onClose: () => {
              this.$refs.staffTable?.requestData()
            }
          })
        }
      })
    }
  }
}
</script>
